package com.enation.app.javashop.core.member.service.impl;

import com.enation.app.javashop.core.geo.model.AddressComponent;
import com.enation.app.javashop.core.geo.model.RegeoCode;
import com.enation.app.javashop.core.geo.service.GaodeManager;
import com.enation.app.javashop.core.member.model.dos.BuyerLastLeaderDO;
import com.enation.app.javashop.core.member.model.dos.LeaderDO;
import com.enation.app.javashop.core.member.model.dos.MemberAddress;
import com.enation.app.javashop.core.member.model.dto.LeaderDTO;
import com.enation.app.javashop.core.member.model.dto.NearLeaderDTO;
import com.enation.app.javashop.core.member.model.vo.LeaderQueryVO;
import com.enation.app.javashop.core.member.model.vo.LeaderVO;
import com.enation.app.javashop.core.member.service.LeaderFansManager;
import com.enation.app.javashop.core.member.service.LeaderManager;
import com.enation.app.javashop.core.statistics.util.DateUtil;
import com.enation.app.javashop.core.trade.order.model.enums.ShipTypeEnum;
import com.enation.app.javashop.core.trade.order.model.vo.CheckoutParamVO;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

@Service
public class LeaderManagerImpl implements LeaderManager {

    @Autowired
    @Qualifier("memberDaoSupport")
    private DaoSupport daoSupport;

    @Autowired
    private GaodeManager gaodeManager;
    @Autowired
    private LeaderFansManager    leaderFansManager;

    @Override
    @Transactional(value = "memberTransactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public LeaderDO addLeader(LeaderDO leaderDO) {
        leaderDO.setStatus(1);
        leaderDO.setAddTime(DateUtil.getDateline());
        leaderDO.setUpdateTime(DateUtil.getDateline());
        daoSupport.insert("es_leader", leaderDO);
        return leaderDO;
    }

    @Override
    @Transactional(value = "memberTransactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean edit(LeaderDO leaderDO, Integer leaderId) {
        daoSupport.update(leaderDO, leaderId);
        return true;
    }

    @Override
    public Page list(LeaderQueryVO queryVO) {
        List<Object> term = new ArrayList<>();
        StringBuilder sql = new StringBuilder("select l.*, m.midentity, m.nickname from es_leader l left join es_member m on m.member_id = l.member_id where 1=1");

        // 站长姓名
        String leaderName = queryVO.getLeaderName();
        if(leaderName != null){
            sql.append(" and l.leader_name like  ?");
            term.add(leaderName);
        }
        // 站长手机号
        String leaderMobile = queryVO.getLeaderMobile();
        if(leaderMobile != null){
            sql.append(" and l.leader_mobile  = ?");
            term.add(leaderMobile);
        }
        // 站点状态
        Integer status = queryVO.getStatus();
        if(status != null){
            sql.append(" and l.status = ?");
            term.add(status);
        }
        // 店铺名称
        String siteName= queryVO.getSiteName();
        if(siteName != null){
            sql.append(" and l.site_name like ?");
            term.add(siteName);
        }

        // 所属社区
        String cellName = queryVO.getCellName();
        if(cellName != null){
            sql.append(" and l.cell_name like ?");
            term.add(cellName);
        }
        // 审核状态
        Integer auditStatus = queryVO.getAuditStatus();
        if(auditStatus != null){
            sql.append(" and l.audit_status = ?");
            term.add(auditStatus);
        }
        // 卖家id
        Integer sellerId = queryVO.getSellerId();
        if(sellerId != null){
            sql.append(" and l.seller_id = ?");
            term.add(sellerId);
        }

        // 营业状态查询
        Integer opStatus = queryVO.getOpStatus();
        if(opStatus != null){
            sql.append(" and l.op_status = ?");
            term.add(opStatus);
        }



        // 状态查询
        Integer siteType = queryVO.getSiteType();
        if(siteType != null){
            sql.append(" and l.site_type = ?");
            term.add(siteType);
        }

        // 站点类型查询
        Integer leaderType = queryVO.getLeaderType();
        if(leaderType != null){
            sql.append(" and l.leader_type = ?");
            term.add(leaderType);
        }


        // 地址查询
        Integer provinceId = queryVO.getProvinceId();
        if(provinceId != null){
            sql.append(" and l.province_id = ?");
            term.add(provinceId);
        }

        // 地址查询
        Integer cityId = queryVO.getCityId();
        if(cityId != null){
            sql.append(" and l.city_id = ?");
            term.add(cityId);
        }

        // 地址查询
        Integer countyId = queryVO.getCountyId();
        if(countyId != null){
            sql.append(" and l.county_id = ?");
            term.add(countyId);
        }

        // 地址查询
        Integer townId = queryVO.getTownId();
        if(townId != null){
            sql.append(" and l.town_id = ?");
            term.add(townId);
        }
        // 城市
        if (StringUtils.isNotEmpty(queryVO.getCity())) {
            sql.append(" and ( l.province = ? or l.city=?)");
            term.add(queryVO.getCity());
            term.add(queryVO.getCity());
        }

        //关键字查询
        String keyword = queryVO.getKeyword();
        if (!StringUtil.isEmpty(keyword)) {
            sql.append(" and (l.leader_name like ? or l.leader_mobile like ? " +
                    "or l.site_name like ? or l.cell_name like ?) ");
            term.add("%" + keyword + "%");
            term.add("%" + keyword + "%");
            term.add("%" + keyword + "%");
            term.add("%" + keyword + "%");
        }

        // 申请时间查询
        Long startTime = queryVO.getStartTime();
        Long endTime = queryVO.getEndTime();
        if (startTime != null && endTime != null) {
            sql.append(" and l.add_time between ? and ?");
            term.add(startTime);
            term.add(endTime);
        }
        sql.append(" order by l.add_time desc");
        return this.daoSupport.queryForPage(sql.toString(), queryVO.getPageNo(),
                queryVO.getPageSize(), LeaderDTO.class, term.toArray());
    }


    /**
     * 根据坐标位置，查询出
     */
    @Override
    public Page<NearLeaderDTO> nearLeaderList(int pageNo, int pageSize, Double lng, Double lat) {
        RegeoCode regeoCode =  gaodeManager.parseLatLng(lng,lat);
        if(regeoCode == null || regeoCode.getAddressComponent()==null || regeoCode.getAddressComponent().getDistrict()==null){
            throw  new ServiceException("601","地址无法解析到对应的区县");
        }
        String municipality = "上海市,北京市,重庆市,天津市";
        AddressComponent addressComponent = regeoCode.getAddressComponent();
        boolean municipalityTag =  municipality.contains(regeoCode.getAddressComponent().getProvince());
        // 查询审核已通过 ，状态已开启
        String targerArea ,sql;
        if(municipalityTag){
            targerArea=addressComponent.getProvince();
            sql = "select * , round((st_distance (point (lng, lat),point(+"+lng+","+lat+") ) * 111195)/1000,2)  AS distance from es_leader  where (province = ? or city=?)  and audit_status = 2 and status=1 order by distance asc  ";
        }else{
            targerArea = addressComponent.getCity();
            sql = "select * , round((st_distance (point (lng, lat),point(+"+lng+","+lat+") ) * 111195)/1000,2)  AS distance from es_leader  where (county = ? or city=?)  and audit_status = 2  and status=1  order by distance asc  ";
        }
        return this.daoSupport.queryForPage(sql,pageNo,pageSize,NearLeaderDTO.class,targerArea,targerArea);
    }

    @Override
    @Transactional(value = "memberTransactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean delete(Integer leaderId) {
        LeaderDO leaderDO = getById(leaderId);
        if(leaderDO == null){
            throw new RuntimeException("团长不存在");
        }
        Page page = leaderFansManager.getListByLeaderId(leaderId, 1, 1);
        List leaderFansList = page.getData();
        if(leaderFansList != null && !leaderFansList.isEmpty()){
            throw new RuntimeException("团长有粉丝，不能删除");
        }
        this.daoSupport.delete(LeaderDO.class, leaderId);
        return true;
    }

    /**
     * 根据客户id , 查询团长信息
     */
    @Override
    public LeaderDO getById(Integer id) {
        return this.daoSupport.queryForObject(LeaderDO.class,id);
    }

    @Override
    public LeaderDO getByMemberId(Integer memberId) {
        String sql = "select * from es_leader where member_id = ?";
        return this.daoSupport.queryForObject(sql, LeaderDO.class, memberId);
    }

    /**
     * 根据会员id 与 店铺id,查询出对应的团长信息
     */
    @Override
    public LeaderDO getLeaderByShopIdAndBuyerId(Integer shopId, Integer buyerId) {
        //根据会员，查询出客户是否有最后的绑定团长id;
        String getLastLeaderSql = "select * from es_buyer_last_leader  where buyer_id = ?";
        BuyerLastLeaderDO lastLeaderDO = this.daoSupport.queryForObject(getLastLeaderSql,BuyerLastLeaderDO.class,buyerId);
        LeaderDO leaderDO =null;
        if(lastLeaderDO!=null){
            //查询出详细的团长信息
            leaderDO = this.daoSupport.queryForObject(LeaderDO.class,lastLeaderDO.getLeaderId());
        }
        return leaderDO;
    }


    /**
     * 根据团长id ，经纬度查询出对应的最后团长信息
     */
    @Override
    public NearLeaderDTO getByIdAndLatLng(Integer id, Double lng, Double lat) {
        String sql = "select * , round((st_distance (point (lng, lat),point(+"+lng+","+lat+") ) * 111195)/1000,2)  AS distance from es_leader  where leader_id = ?  ";
        return this.daoSupport.queryForObject(sql,NearLeaderDTO.class,id);
    }

    @Override
    public NearLeaderDTO getNearestLeader(Double lng, Double lat) {
        String sql = "select * , round((st_distance (point (lng, lat),point(+"+lng+","+lat+") ) * 111195)/1000,2)  AS distance from es_leader  where audit_status ="+2 +" order by distance asc ";
        return this.daoSupport.queryForObject(sql,NearLeaderDTO.class);
    }

    @Override
    public LeaderDO getBandLeader(Integer uid) {
        BuyerLastLeaderDO lastLeader = leaderFansManager.getLastLeader(uid);
        if (lastLeader == null) {
            return null;
        }
        return this.getById(lastLeader.getLeaderId());
    }
    @Override
    public void updateLeaderStatus(String leaderIds, Integer status){
        if(StringUtil.isEmpty(leaderIds)){
            throw new RuntimeException("请选择启用或禁用的站点");
        }
        List<LeaderDO> list = this.getLeaderDO(leaderIds);
        for (LeaderDO leaderDo : list){
            if(leaderDo != null){
                leaderDo.setStatus(status);
               this.edit(leaderDo,leaderDo.getLeaderId());
            }
        }
    }

    @Override
    public List<LeaderDO> getLeaderDO(String leaderIds){
        String sql = " select * from es_leader  where leader_id in(" + leaderIds + ") ";
        return daoSupport.queryForList(sql, LeaderDO.class);
    }

    @Override
    public LeaderDO getLeaderDOByLeaderId(Integer leaderId) {
        String sql = " select * from es_leader  where leader_id = ?";
        return daoSupport.queryForObject(sql, LeaderDO.class, leaderId);
    }

    @Override
    public void updatePriority(Integer leaderId, Integer shipPriority) {
        String sql = " UPDATE es_leader SET ship_priority= ? where leader_id = ?";
        daoSupport.execute(sql, shipPriority, leaderId);
    }

    @Override
    public List<LeaderVO> queryLeaderBySiteName(String siteName) {
        String sql = "SELECT * from es_leader where site_name like ? ";
        return daoSupport.queryForList(sql, LeaderVO.class, "%" + siteName + "%");
    }

    @Override
    public LeaderDO getLeaderDO(CheckoutParamVO param, MemberAddress memberAddress, String activeShipWay) {
        LeaderDO leaderDO =null;
        if(activeShipWay.equals(ShipTypeEnum.SELF.name())){
            if(param.getSiteId()==null){
                leaderDO = this.getBandLeader(UserContext.getBuyer().getUid()) ;
                if(leaderDO==null){
                    throw new ServiceException("500","请切换使用快递到家");
                }
                param.setSiteId(leaderDO.getLeaderId());
            }else{
                leaderDO = this.getById(param.getSiteId()) ;
            }
            Assert.notNull(leaderDO, "必须选择自提点");
        }
        if(activeShipWay.equals(ShipTypeEnum.GLOBAL.name()) && memberAddress==null ){
            throw new ServiceException("500","必须选择收货地址");
        }
        if(leaderDO!=null && leaderDO.getCity()!=null && param!=null && param.getCity()!=null && !param.getCity().equals("undefined")  &&  (!leaderDO.getCity().equals(param.getCity()) && !leaderDO.getProvince().equals(param.getCity()))){
            throw new ServiceException("500","自提站点【"+leaderDO.getCity()+"】与所属城市【"+param.getCity()+"】,不在同一个城市,请切换城市;");
        }
        return leaderDO;
    }
}
